<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>抖音视频下载插件测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .test-section h3 {
            margin-top: 0;
            color: #666;
        }
        button {
            background: #007cba;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #005a87;
        }
        .log {
            background: #f8f8f8;
            border: 1px solid #ddd;
            padding: 10px;
            margin: 10px 0;
            border-radius: 3px;
            font-family: monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 3px;
        }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎬 抖音视频下载插件测试</h1>
        
        <div class="test-section">
            <h3>📋 插件状态检查</h3>
            <button onclick="checkExtension()">检查插件是否加载</button>
            <button onclick="checkPermissions()">检查权限</button>
            <div id="extensionStatus" class="status info">点击按钮开始检查...</div>
        </div>

        <div class="test-section">
            <h3>🔗 模拟抖音环境</h3>
            <p>这个页面模拟抖音环境来测试插件功能</p>
            <video id="testVideo" controls width="300" height="200" style="display: block; margin: 10px 0;">
                <source src="https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4" type="video/mp4">
                您的浏览器不支持视频标签。
            </video>
            <div data-e2e="video-desc" class="video-desc">测试视频标题 - 抖音插件功能验证</div>
        </div>

        <div class="test-section">
            <h3>🧪 功能测试</h3>
            <button onclick="testContentScript()">测试Content Script</button>
            <button onclick="testBackgroundScript()">测试Background Script</button>
            <button onclick="testVideoExtraction()">测试视频提取</button>
            <button onclick="simulateDownload()">模拟下载</button>
            <div id="testResults" class="status info">等待测试...</div>
        </div>

        <div class="test-section">
            <h3>📝 调试日志</h3>
            <button onclick="clearLog()">清空日志</button>
            <button onclick="exportLog()">导出日志</button>
            <div id="debugLog" class="log">日志将在这里显示...</div>
        </div>
    </div>

    <script>
        let logContainer = document.getElementById('debugLog');
        
        function log(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] ${message}`;
            console.log(logEntry);
            
            const logElement = document.createElement('div');
            logElement.textContent = logEntry;
            logElement.style.color = type === 'error' ? 'red' : type === 'success' ? 'green' : 'black';
            logContainer.appendChild(logElement);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        function updateStatus(elementId, message, type = 'info') {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.className = `status ${type}`;
        }

        async function checkExtension() {
            log('开始检查插件状态...');
            
            if (typeof chrome === 'undefined' || !chrome.runtime) {
                updateStatus('extensionStatus', '❌ Chrome扩展API不可用', 'error');
                log('Chrome扩展API不可用', 'error');
                return;
            }

            try {
                const manifest = chrome.runtime.getManifest();
                updateStatus('extensionStatus', `✅ 插件已加载: ${manifest.name} v${manifest.version}`, 'success');
                log(`插件已加载: ${manifest.name} v${manifest.version}`, 'success');
                log(`权限: ${JSON.stringify(manifest.permissions)}`, 'info');
                log(`主机权限: ${JSON.stringify(manifest.host_permissions)}`, 'info');
            } catch (error) {
                updateStatus('extensionStatus', '❌ 无法获取插件信息', 'error');
                log(`获取插件信息失败: ${error.message}`, 'error');
            }
        }

        async function checkPermissions() {
            log('检查权限...');
            
            const permissions = ['downloads', 'webRequest', 'storage', 'scripting'];
            const hosts = ['*://*.douyin.com/*', '*://*.douyinvod.com/*'];
            
            for (const permission of permissions) {
                try {
                    const hasPermission = await chrome.permissions.contains({permissions: [permission]});
                    log(`权限 ${permission}: ${hasPermission ? '✅' : '❌'}`, hasPermission ? 'success' : 'error');
                } catch (error) {
                    log(`检查权限 ${permission} 失败: ${error.message}`, 'error');
                }
            }
            
            for (const host of hosts) {
                try {
                    const hasPermission = await chrome.permissions.contains({origins: [host]});
                    log(`主机权限 ${host}: ${hasPermission ? '✅' : '❌'}`, hasPermission ? 'success' : 'error');
                } catch (error) {
                    log(`检查主机权限 ${host} 失败: ${error.message}`, 'error');
                }
            }
        }

        async function testContentScript() {
            log('测试Content Script...');
            
            try {
                // 模拟content script的功能
                const videoInfo = {
                    url: document.querySelector('video')?.src || 'https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4',
                    title: document.querySelector('[data-e2e="video-desc"]')?.textContent || '测试视频',
                    timestamp: Date.now()
                };
                
                log(`提取的视频信息: ${JSON.stringify(videoInfo)}`, 'success');
                updateStatus('testResults', '✅ Content Script测试通过', 'success');
            } catch (error) {
                log(`Content Script测试失败: ${error.message}`, 'error');
                updateStatus('testResults', '❌ Content Script测试失败', 'error');
            }
        }

        async function testBackgroundScript() {
            log('测试Background Script通信...');
            
            try {
                const response = await chrome.runtime.sendMessage({type: 'GET_VIDEO_URLS'});
                log(`Background响应: ${JSON.stringify(response)}`, 'success');
                updateStatus('testResults', '✅ Background Script通信正常', 'success');
            } catch (error) {
                log(`Background Script通信失败: ${error.message}`, 'error');
                updateStatus('testResults', '❌ Background Script通信失败', 'error');
            }
        }

        async function testVideoExtraction() {
            log('测试视频提取功能...');
            
            const videos = document.querySelectorAll('video');
            log(`找到 ${videos.length} 个video元素`);
            
            videos.forEach((video, index) => {
                log(`Video ${index + 1}: src=${video.src}, currentSrc=${video.currentSrc}`);
            });
            
            const resources = performance.getEntriesByType('resource');
            const videoResources = resources.filter(r => 
                r.name.includes('.mp4') || 
                r.name.includes('video') || 
                r.name.includes('sample-videos')
            );
            
            log(`找到 ${videoResources.length} 个视频资源:`);
            videoResources.forEach(resource => {
                log(`资源: ${resource.name}`);
            });
            
            updateStatus('testResults', `✅ 找到 ${videos.length} 个视频元素，${videoResources.length} 个视频资源`, 'success');
        }

        async function simulateDownload() {
            log('模拟下载请求...');
            
            const testVideoUrl = 'https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4';
            const testTitle = '测试视频下载';
            
            try {
                const response = await chrome.runtime.sendMessage({
                    type: 'DOWNLOAD_VIDEO',
                    url: testVideoUrl,
                    title: testTitle,
                    timestamp: Date.now(),
                    uniqueId: Math.random().toString(36).substr(2, 9)
                });
                
                log(`下载响应: ${JSON.stringify(response)}`, response.success ? 'success' : 'error');
                updateStatus('testResults', response.success ? '✅ 下载请求成功' : '❌ 下载请求失败', response.success ? 'success' : 'error');
            } catch (error) {
                log(`下载请求失败: ${error.message}`, 'error');
                updateStatus('testResults', '❌ 下载请求失败', 'error');
            }
        }

        function clearLog() {
            logContainer.innerHTML = '日志已清空...';
        }

        function exportLog() {
            const logText = logContainer.textContent;
            const blob = new Blob([logText], {type: 'text/plain'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `plugin-test-log-${new Date().toISOString().slice(0,19).replace(/:/g,'-')}.txt`;
            a.click();
            URL.revokeObjectURL(url);
        }

        // 页面加载完成后自动检查
        window.addEventListener('load', () => {
            log('测试页面加载完成');
            setTimeout(checkExtension, 1000);
        });

        // 监听来自插件的消息
        if (typeof chrome !== 'undefined' && chrome.runtime) {
            chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
                log(`收到插件消息: ${JSON.stringify(message)}`);
                
                if (message.type === 'GET_VIDEO_INFO') {
                    const videoInfo = {
                        url: document.querySelector('video')?.src || 'https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4',
                        title: document.querySelector('[data-e2e="video-desc"]')?.textContent || '测试视频',
                        timestamp: Date.now()
                    };
                    sendResponse(videoInfo);
                    log(`返回视频信息: ${JSON.stringify(videoInfo)}`);
                }
                
                return true;
            });
        }
    </script>
</body>
</html>